import user from '@/api/user.js'
import me from '@/api/me.js'
import chat from '@/api/chat.js'
import store from '@/store/index.js'
import tim from '@/utils/commen/tim.js'
import TIM from '@/utils/tim/tim-js-sdk'
// tim登录
function timLogin(callback) {
  let defaultAvatar = 'https://files.yzsheng.com/AccountDefaultImg/HeadPortrait.png'
  if(uni.getStorageSync('token')) {
    Promise.all([user.GetUserInfomation(), me.getMyInfo()]).then(async data => {
      let userinfo = data[0]
      let myInfo = data[1]
      let res = await chat.getTimInfo({
        storeId: userinfo.data.accountid
      })
      store.commit('timUserInfo', {
        userId: res.data.userid,
        user: res.data.username || userinfo.data.nickname,
        img: userinfo.data.headportrait || defaultAvatar,
        userSig: res.data.usersig,
        isService: myInfo.data.isService,
        invitecode: userinfo.data.invitecode
      })

      tim.tim.login({
        userID: res.data.userid,
        userSig: res.data.usersig,
      }).then(res => {
        let user = store.state.timUserInfo

        if(store.state.isSDKReady) {
          tim.tim.updateMyProfile({
            nick: userinfo.data.nickname,
            avatar: userinfo.data.headportrait || defaultAvatar
          }).then(imResponse => {
          }).catch(function(imError) {
          })

          callback && callback()
        } else {
          tim.tim.on(TIM.EVENT.SDK_READY, data => {
            tim.tim.updateMyProfile({
              nick: userinfo.data.nickname,
              avatar: userinfo.data.headportrait || defaultAvatar
            }).then(imResponse => {
            }).catch(function(imError) {
            })

            store.commit('isSDKReady', true)
            callback && callback()
          }, this)
        }
      }).catch(err => {
        uni.hideLoading()
        uni.showToast({
          icon: 'none',
          title: 'IM登录失败'
        })
        console.warn('login error:', err) // 登录失败的相关信息
      })
    }).catch(err => {})
  }
}

export default timLogin